import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {BaseService} from '../../../shared/service/base.service';
import {validMoney} from '../../../shared/validator/validator';
import {ApiUrl} from '../../../config/api-url';

@Component({
  selector: 'app-merchant-manage-edit',
  templateUrl: './merchant-manage-edit.component.html',
  styleUrls: ['./merchant-manage-edit.component.less']
})
export class MerchantManageEditComponent implements OnInit {
// 模态框显隐
  @Input()
  isVisible = false;
  @Input()
  feedback: any;
  // 父子互传值
  @Output()
  emit: EventEmitter<any> = new EventEmitter();
  // 提交时提交按钮是否加载中
  isOkLoading: any;
  // 模态框表单
  formModel: FormGroup;
  title: any;
  payCompanyCodeList: any;
  constructor(private fb: FormBuilder, private baseService: BaseService) { }

  ngOnInit(): void {
    this.buildForm();
  }
  ngOnChanges() {
    if (this.feedback != null) {
      this.title = '编辑渠道'
      this.formModel.reset({
        id: this.feedback.id,
        payCompanyCode: this.feedback.payCompanyCode,
        merchantId: this.feedback.merchantId,
        outTradeNo: this.feedback.outTradeNo
      });
      this.payCompanyCodeLoad();
    }
  }
  buildForm() {
    this.formModel = this.fb.group({
      id: [0,[]],
      payCompanyCode: [null, [Validators.required]],
      merchantId: [null,[]],
      outTradeNo: [null,[]]
    });
  }
  payCompanyCodeLoad(){
    this.baseService.get(ApiUrl.MerchantPayCompanyUrl + "/findMerchantPayCompany?merchantId=" + this.feedback.merchantId).subscribe(res => {
      this.payCompanyCodeList = res.data;
    })
  }
  // 取消
  handleCancel() {
    this.isVisible = false;
    this.feedback = null;
    this.formModel.reset({
      id: 0,
      payCompanyCode: null,
      merchantId: null,
      outTradeNo: null
    });
    this.emit.emit(this.isVisible);
  }

  // 确认
  handleOk() {
    this.isOkLoading = true;
    if (!this.baseService.zorro.validateFormValidate(this.formModel)) {
      this.isOkLoading = false;
      return;
    }

    if (!this.isOkLoading) {
      return;
    }
    this.baseService.post(ApiUrl.MerchantUrl + '/switchoverPayCompany', this.formModel.value).subscribe(res => {
      if (res.status == 0) {
        this.baseService.layer.messageSuccess(this.formModel.controls['id'].value > 0 ? "修改成功" : "添加成功");
        this.handleCancel();
        this.isOkLoading = false;
      } else {
        this.baseService.layer.messageError(res.msg);
        this.isOkLoading = false;
      }
    });
  }
}
